package my.study.c.consul.consumer.app.configuration;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Iterator;
import java.util.Optional;

@Slf4j
@Component
public class FeignRequestInterceptor implements RequestInterceptor {

    @Value("${feign.token}")
    String token;

    @Override
    public void apply(RequestTemplate template) {
        log.info("Feign 调用, url: {} ", template.request().url());

        HttpServletRequest request = Optional.ofNullable(RequestContextHolder.getRequestAttributes()).map(it -> ((ServletRequestAttributes) it).getRequest()).orElse(null);
        if (request == null) {
            return;
        }
        template.header("Authorization", token);

        /*
          此处代码为使用拦截器把token传递给调用的服务提供者
          示例项目不需要传递token, 直接在服务消费者和服务提供者之间定义一个token提供者鉴权消费者的token是否一致
        */
//        Iterator<String> headerIterator = CollectionUtils.toIterator(request.getHeaderNames());
//        while (headerIterator.hasNext()) {
//            String name = headerIterator.next();
//            log.info("add header, url: {} , path: {}", name, request.getHeader(name));
//            只写入 Authorization
//            if (BaseConstants.HEADER_KEY_TOKEN.equals(name)) {
//            if ("Authorization".equals(name)) {
//                template.header(name, request.getHeader(name));
//            }
//        }

    }
}
